package com.ruike.alisurface.ui.payPage;

import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TextView;

import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.ICCardUtils;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.CardInfoBean;
import com.ruike.alisurface.bean.CardOrderBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.CardHttp;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.TimeUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PayCardActivity extends BaseAty implements ICCardUtils.OnICCardListener {


    @BindView(R.id.payCard_operationTips_tv)
    TextView operationTipsTv;
    @BindView(R.id.payCard_payInfo_tabLayout)
    TableLayout payInfoTabLayout;
    @BindView(R.id.payCard_cardNumber_tv)
    TextView cardNumberTv;
    @BindView(R.id.payCard_payPrice_tv)
    TextView payPriceTv;
    @BindView(R.id.payCard_yemoney_tv)
    TextView yemoneyTv;
    @BindView(R.id.payCard_payTime_tv)
    TextView payTimeTv;
    @BindView(R.id.payCard_countTime_tv)
    TextView countTimeTv;

    List<CarGoodsBeans> paycarlist;
    double monry = 0.0f;
    List<Integer> slotIndexList;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_card;
    }

    @Override
    protected void initViews() {
        startCountdownTimer(120, countTimeTv, SelectPayTypeActivity.class);
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        ICCardUtils.setOnICCardListener(this);

        // 计算购物车商品的总金额并展示在界面上
        paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        if (paycarlist != null && paycarlist.size() > 0) {
            slotIndexList = new ArrayList<>();
        } else {
            return;
        }
        slotIndexList.clear();
        for (CarGoodsBeans carGoodsBean : paycarlist) {
            if (carGoodsBean != null && carGoodsBean.getPrice() > 0) {
                monry += carGoodsBean.getPrice();
                slotIndexList.add(Integer.parseInt(carGoodsBean.getSlotIndexs()));
            }
        }
        payPriceTv.setText(new StringBuffer("¥").append(monry));
    }

    @Override
    protected void onResume() {
        super.onResume();
        ICCardUtils.oneKeyReadCard();
    }

    @OnClick({R.id.payCard_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.payCard_goback_imgv:
                startActivity(SelectPayTypeActivity.class, null);
                finish();
                break;
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onICCardNumberLisyener(byte[] hexNumber, String cardNumber) {
        cardNumberTv.setText(cardNumber);
        CardHttp.queryCardNo(cardNumber, this);
    }

    ShopDetailBean shopDetailBean;

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("Card/QueryCardNo")) {
            CardInfoBean cardInfoBean = GsonUtils.json2Model(requestJsonStr, CardInfoBean.class);
            yemoneyTv.setText(String.valueOf(cardInfoBean.getData().getBalance()));
            if (cardInfoBean.getData().getBalance() > monry) {
                operationTipsTv.setVisibility(View.GONE); // 隐藏刷卡提示
                payInfoTabLayout.setVisibility(View.VISIBLE); // 展示开信息的提示
                String currentTimeStr = TimeUtils.millis2String(System.currentTimeMillis());
                payTimeTv.setText(currentTimeStr);

                String mchid = ShareUtils.getInstance().getString(ShareKey.MCH_ID, "");
                String cardno = cardInfoBean.getData().getCardno();
                JSONArray jsonArray = new JSONArray();
                for (int soltIndex : slotIndexList) {
                    JSONObject orderDetailsJson = new JSONObject();
                    try {
                        orderDetailsJson.put("Quantity", 1);
                        orderDetailsJson.put("SlotIndex", soltIndex);
                    } catch (JSONException e) {
                        L.e("刷卡支付界面创建订单JSON字符串拼接创建异常....");
                    }
                    jsonArray.put(orderDetailsJson);
                }

                CardHttp.createOrder(mchid, cardno, "104", currentTimeStr, monry, monry, jsonArray.toString(), PayCardActivity.this);

            } else {
                showErrorTip("卡余额不足，不能完成支付，请先进行充值...");
            }
            return;
        }
        if (requestUrl.endsWith("Card/CreateOrder")) {

            SystemClock.sleep(2000);

            CardOrderBean cardOrderBean = GsonUtils.json2Model(requestJsonStr, CardOrderBean.class);

            shopDetailBean = new ShopDetailBean(cardOrderBean.getData().getOrder().getOrderNo());
            shopDetailBean.setPromotion_fee(cardOrderBean.getData().getOrder().getPromotion_fee());
            shopDetailBean.setTotal_fee(cardOrderBean.getData().getOrder().getTotal_fee());
            shopDetailBean.setPay_fee(cardOrderBean.getData().getOrder().getPay_fee());
            List<ShopDetailBean.OrderDetailsBean> shopOrderDetailsBeanList = new ArrayList<>();
            shopOrderDetailsBeanList.clear();

            for (CardOrderBean.DataBean.OrderBean.OrderDetailsBean cardOrderDetailBean : cardOrderBean.getData().getOrder().getOrderDetails()) {
                ShopDetailBean.OrderDetailsBean shopOrderDetailsBean = new ShopDetailBean.OrderDetailsBean();

                shopOrderDetailsBean.setSlotTypeId(cardOrderDetailBean.getSlotTypeId()); // 货道类型
                shopOrderDetailsBean.setSlotIndex(cardOrderDetailBean.getSlotIndex()); // 出货货道编号
                shopOrderDetailsBean.setQuantity(cardOrderDetailBean.getQuantity()); // 出货数量

                shopOrderDetailsBeanList.add(shopOrderDetailsBean);
            }

            shopDetailBean.setDetailOrderList(shopOrderDetailsBeanList);

            Bundle bundle = new Bundle();
            bundle.putString("pay_type", "weCard");
            bundle.putSerializable("orderrBeanData", shopDetailBean);
            startActivity(PayShowShopActivity.class, bundle);
            finish();
            return;
        }
    }

    @Override
    public void onError(String requestUrl, String requestMsg) {
        super.onError(requestUrl, requestMsg);
        L.e(requestUrl + " Result onError:" + requestMsg);
    }

}
